const username = '15351217062';
const password = 'CT15351217062';
// var verifyCode = 'n8ul';

var superagent = require('superagent');
var str = '';  //图片base64字符串
var _session = '';  //请求图片时的获取的set-cookie
var cookie = '';  //登录接口获取的set-cookie
var finalData = ''; //获取到的短信通知记录
var exportData = []; //导出的数据
var reqCount = 0;
var _info = '';  //响应的info信息
var _mobile = []; //完整手机号
var finalState = false; //最终完成状态

var connect = require('connect')  //创建连接
var bodyParser = require('body-parser')  //body解析

// const hostname = '192.168.1.103'
const hostname = '172.27.0.7'
const port = 3300

var app = connect()
    .use(bodyParser.json())   //JSON解析
    .use(bodyParser.urlencoded({extended: true}))
    //use方法还有一个可选的路径字符串，对传入请求的URL开始匹配
    //use方法来维护一个中间件队列
    .use(function(req, res, next) {
        //跨域处理
        res.setHeader('Access-Control-Allow-Origin', '*')
        res.setHeader('Access-Control-Allow-Credentials', true)
        res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE')
        res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Session-Token')
        res.writeHead(200, {"Content-Type": "text/plain;charset=utf-8"})
        next()    //next 方法就是一个递归调用
    })
    .use('/getCode', function(req, res, next) {  //本地接口---获取验证码
        //中间件
        // console.log(req.body)
        str = '';
        getSession();
        var codeTimer = setInterval(() => {
            if(str) {
                var data = {imgUrl: 'data:image/jpeg;base64,'+str,_session:_session}
                res.end(JSON.stringify(data))
                clearInterval(codeTimer)
            }
        }, 40)
        next()
    })
    .use('/getSession', function (req, res, next) { //本地接口---获取Cookie请求头
        getCookie(req.body.code,req.body._session)
        var cookieTimer = setInterval(() => {
            if(cookie) {
                var data = {data: cookie}
                res.end(JSON.stringify(data))
                clearInterval(cookieTimer)
            }
        }, 40)
        setTimeout(() => {
            if(_info.statusCode === '610') {
                res.end(JSON.stringify(_info))
                clearInterval(cookieTimer)
                return false
            }
        }, 300)
        next()
    })
    .use('/getData', function (req, res, next) { //本地接口---获取短信记录数据
        requestData(req.body._session,req.body.page)
        var timer = setInterval(() => {
            var data = finalData
            if(data.status) {
                res.end(JSON.stringify(data))
                clearInterval(timer)
            }
        }, 50)
        next()
    })
    .use('/process', function (req, res, next) {
        var timer = setInterval(() => {
            if(finalState) {
                var data = {code: 0, msg: 'ok'}
                res.end(JSON.stringify(data))
                clearInterval(timer)
            }else {
                var data = {code: -1, msg: 'not complete'}
                res.end(JSON.stringify(data))
            }
        }, 0)
        next()
    })
    .listen(port, hostname, () => {
        console.log(`Server running at http://${hostname}:${port}/`)
    });

function getSession() {
    var randomNum = ''
    for(var i=0;i<17;i++){
        randomNum += Math.floor(Math.random()*10)
    }
    superagent
        .get(`https://kdcs.zto.cn/nologin/verifyCode?codeType=1&&d=0.${randomNum}`)
        .end(function (err,res) {
            str = res.body.toString('base64');
            _session = res.header['set-cookie'].toString().split(';')[0];
        })
}

function getCookie(code,session) {  //获取快递超市登录接口返回的set-cookie
    superagent
        .post('https://kdcs.zto.cn/user/login')
        .set({
            Accept: "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            Connection: "keep-alive",
            "Content-Type": "application/x-www-form-urlencoded",
            Cookie: session,
            Host: "kdcs.zto.cn",
            Origin: "https://kdcs.zto.cn",
            Referer: "https://kdcs.zto.cn/",
            // "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
        })
        .send({
            username: username,
            password: password,
            verifyCode: code,
        })
        .end(function(err, res) {
            if (err) {
                console.log(err);
                return;
            }
            _info = JSON.parse(res.text)
            if(_info.status) {
                var _cookie = res.header['set-cookie'].toString().split(';')[0];
                cookie = _cookie;
            }

        })
}

function requestData(session,page) { //获取快递超市短信记录数据
    superagent.post('https://kdcs.zto.cn/noticeMsg/page')
        // .withCredentials()//跨域
        .set({
            Accept: "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            Connection: "keep-alive",
            Cookie: session,
            Host: "kdcs.zto.cn",
            Origin: "https://kdcs.zto.cn",
            Referer: "https://kdcs.zto.cn/",
        })
        .type('application/json;charset=UTF-8')
        .send({
            billCode: "",
            endDate: dateLong2String(new Date().getTime()),
            mobile: "",
            // notifyType: "0",
            pageIndex: page,
            pageSize: 100,
            path: 2,
            startDate: dateLong2String(new Date().getTime()),
            status: "5",
            type: "0"
        })
        .end(function(err,res){
            // 常规的错误处理
            if (err) {
                console.log(err.message);
                return;
            }

            finalData = JSON.parse(res.text)

            // console.log(finalData.result)
            if(finalData.status) {
                reqCount++
                for(item of finalData.result.items) {
                    exportData.push(item)
                }

                var _smscount = 0
                if(reqCount === Math.ceil(finalData.result.recordCount/100)) {
                    function _timer() {
                        var smsTimer = setInterval(() => {
                            getSmsDetail(session, exportData[_smscount].id)
                            _smscount++
                            if(_smscount === exportData.length) {
                                for(k in exportData) {
                                    for(k2 in _mobile) {
                                        if(exportData[k].id === _mobile[k2].id) {
                                            exportData[k].mobile = _mobile[k2].receiveManMobile
                                            if(k === k2) {
                                                /!* 如果没有导入xlsx组件则导入 *!/
                                                if(typeof XLSX == 'undefined') XLSX = require('xlsx');

                                                /!* 创建worksheet *!/
                                                var ws = XLSX.utils.json_to_sheet(exportData);

                                                /!* 新建空workbook，然后加入worksheet *!/
                                                var wb = XLSX.utils.book_new();
                                                XLSX.utils.book_append_sheet(wb, ws, "快递超市短信通知数据");

                                                /!* 生成xlsx文件 *!/
                                                XLSX.writeFile(wb, "express.xlsx");

                                                //一段时间后删除生成的xlsx文件，并重置各个信息
                                                // setTimeout(() => {
                                                    str = '';  //图片base64字符串
                                                    _session = '';  //请求图片时的获取的set-cookie
                                                    cookie = '';  //登录接口获取的set-cookie
                                                    finalData = ''; //获取到的短信通知记录
                                                    exportData = []; //导出的数据
                                                    reqCount = 0;
                                                    _info = '';  //响应的info信息
                                                    _mobile = []; //完整手机号
                                                    finalState = false; //最终完成状态
                                                // }, 10000)

                                            }
                                        }
                                    }
                                }
                                clearInterval(smsTimer)
                            }
                        }, 0)
                    }
                    _timer()
                }
            }
        });
}

function getSmsDetail(session, id) {
    superagent.post('https://kdcs.zto.cn/public/getSmsDetail')
        // .withCredentials()//跨域
        .set({
            Accept: "application/json, text/plain, */*",
            "Accept-Encoding": "gzip, deflate, br",
            "Accept-Language": "zh-CN,zh;q=0.9",
            Connection: "keep-alive",
            Cookie: session,
            Host: "kdcs.zto.cn",
            Origin: "https://kdcs.zto.cn",
            Referer: "https://kdcs.zto.cn/",
            "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36"
        })
        .type('application/json;charset=UTF-8')
        .send({
            id: id
        })
        .end(function (err, res) {
            if (err) {
                console.log(err.message);
                getSmsDetail(session,id)
                return;
            }
            var data = JSON.parse(res.text)
            _mobile.push({id:data.result.id,receiveManMobile:data.result.receiveManMobile})
            if(finalData.result.recordCount === _mobile.length) {
                finalState = true
            }
            console.log(data.result.receiveManMobile,data.result.id,_mobile.length,finalData.result.recordCount)
        })
}

//时间戳转为yyyy-MM-dd格式
function dateLong2String(time){
    var date = new Date(time);
    var year = date.getFullYear();
    var month = date.getMonth()+1;
    var day = date.getDate();
    month = month < 10 ? "0"+month:month;
    day = day < 10 ? "0"+day:day;
    return year+"-"+month+"-"+day;
};